package com.xzy.urp.controller;


import cn.hutool.core.bean.BeanUtil;
import com.xzy.urp.common.exception.Assert;
import com.xzy.urp.common.exception.BusinessException;
import com.xzy.urp.common.result.R;
import com.xzy.urp.common.result.ResponseEnum;
import com.xzy.urp.pojo.entity.CourseInfo;
import com.xzy.urp.pojo.entity.CourseTime;
import com.xzy.urp.pojo.entity.TeacherInfo;
import com.xzy.urp.pojo.vo.*;
import com.xzy.urp.service.BaseInfoService;
import com.xzy.urp.service.CourseSelectionService;
import com.xzy.urp.service.CourseTimeService;
import com.xzy.urp.service.TeacherInfoService;
import com.xzy.urp.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xzy
 * @since 2022-02-17
 */
@RestController
@RequestMapping("/admin/teacherInfo")
@Api(tags = "教师信息管理接口")
public class TeacherInfoController {


//教师信息录入
//个人信息查询
//课程信息维护
//成绩录入
//教师课表

    private final TeacherInfoService teacherInfoService;

    private final CourseTimeService courseTimeService;

    private final BaseInfoService baseInfoService;

    private final CourseSelectionService courseSelectionService;

    public TeacherInfoController(TeacherInfoService teacherInfoService, CourseTimeService courseTimeService,
                                 BaseInfoService baseInfoService, CourseSelectionService courseSelectionService) {
        this.teacherInfoService = teacherInfoService;
        this.courseTimeService = courseTimeService;
        this.baseInfoService = baseInfoService;
        this.courseSelectionService = courseSelectionService;
    }

    @ApiOperation("教师信息录入（管理员权限）")
    @PostMapping("/add")
    public R tInfoEntry(@ApiParam("教师信息视图")
                            @RequestBody TeacherInfoVO teacherInfoVO) {


        if (teacherInfoService.addTInfo(teacherInfoVO)){
            return R.ok().message("录入成功");
        }
        return R.error().message("录入失败");

    }


    @ApiOperation("教师个人信息查询")
    @GetMapping("/getInfo")
    public R tInfoQuery(HttpServletRequest request) {
        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
        Long userId = JwtUtils.getUserId(token);
        TeacherInfo teacherInfo = teacherInfoService.getInfoById(userId);
        TeacherInfoVO teacherInfoVO = new TeacherInfoVO();
        BeanUtil.copyProperties(teacherInfo,teacherInfoVO);
        return R.ok().message("获取成功").data("teacherInfoVO",teacherInfoVO);
    }


    @ApiOperation("个人所授课程列表")
    @GetMapping("/listCourse/{year}")
    public R courseList(HttpServletRequest request,
                        @ApiParam("学年信息") @PathVariable Integer year) {
        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
        Long userId = JwtUtils.getUserId(token);
        List<CourseInfo> courseInfoList = teacherInfoService.getCInfoById(userId, year);

        List<CourseInfoVO> courseInfoVOS = new ArrayList<>();

        courseInfoList.forEach(e->{
            CourseInfoVO courseInfoVO = new CourseInfoVO();
            BeanUtil.copyProperties(e,courseInfoVO);
            courseInfoVOS.add(courseInfoVO);
        });

        return R.ok().message("获取成功").data("list",courseInfoVOS);
    }
    @ApiOperation("个人课表")
    @GetMapping("/listTimeTable/{year}")
    public R tSchedule(HttpServletRequest request,
                       @ApiParam("学年信息") @PathVariable Integer year) {
        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
        Long userId = JwtUtils.getUserId(token);
        List<CourseTimeVO> courseTimes = teacherInfoService.getCTimeById(userId, year);


        return R.ok().message("获取成功").data("list",courseTimes);
    }
    @ApiOperation("添加课程")
    @PostMapping("/addCourse")
    public R addCourse(HttpServletRequest request,@ApiParam("课程信息") @RequestBody CourseInfoVO courseInfoVO) {
        // 添加课程信息
        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
        Long userId = JwtUtils.getUserId(token);
        courseInfoVO.setTeacherId(userId);
        teacherInfoService.addCInfo(courseInfoVO);
        return R.ok().message("添加成功");
    }
    @ApiOperation("课程信息修改")
    @PostMapping("/updateCourse")
    public R updateCourse(HttpServletRequest request,@ApiParam("课程信息") @RequestBody CourseInfoVO courseInfoVO) {
        //修改课程基本信息
        teacherInfoService.updateCInfo(courseInfoVO);

        return R.ok().message("修改成功");
    }

    @ApiOperation("排课")
    @PostMapping("/arrangeCourse")
    public R arrangeCourse(HttpServletRequest request,@ApiParam("排课信息") @RequestBody ArrangeVO arrangeVO) {
        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)
        Long userId = JwtUtils.getUserId(token);
        // 查询周期内是否有课
        Boolean plan = courseTimeService.isPlan(userId, arrangeVO.getStartWeeks(), arrangeVO.getEndWeeks());
        // 查询教室是否可用
        Boolean addable = baseInfoService.isAddable(arrangeVO.getSemester(), arrangeVO.getSection(),
                arrangeVO.getStartWeeks(), arrangeVO.getEndWeeks(), arrangeVO.getBaseId());

        Assert.isTrue(plan,ResponseEnum.SCHEDULING_CONFLICT);
        Assert.isTrue(addable,ResponseEnum.CLASSROOM_OCCUPIED);

        CourseTime courseTime = new CourseTime();
        courseTime.setCourseId(arrangeVO.getCId());
        courseTime.setBaseId(arrangeVO.getBaseId());
        courseTime.setStartWeeks(arrangeVO.getStartWeeks());
        courseTime.setEndWeeks(arrangeVO.getEndWeeks());
        courseTime.setSection(arrangeVO.getSection());
        courseTime.setSemester(arrangeVO.getSemester());
        // 添加课程安排信息
        courseTimeService.save(courseTime);

        return R.ok().message("置入成功");
    }
    @ApiOperation("课程删除")
    @PostMapping("/removeCourse")
    public R removeCourse(@ApiParam("排课信息") @RequestBody Long CId) {

        teacherInfoService.removeCInfo(CId);
        courseTimeService.removeCtime(CId);
        return R.ok().message("删除成功");
    }
    @ApiOperation("成绩录入")
    @PostMapping("/gradeEntry/{sId}/{grade}/{CId}")
    public R gradeEntry(@ApiParam("学生id") @PathVariable Long sId,@ApiParam("成绩") @PathVariable Double grade,@ApiParam("课程号") @PathVariable Integer CId) {
        courseSelectionService.gradeEntry(sId,grade,CId);
        return R.ok().message("录入成功");
    }
    @ApiOperation("成绩列表")
    @GetMapping("/ListGrade/{cid}")
    public R ListGrade(@ApiParam("课程号") @PathVariable Integer cid) {
        List<GradeVO> gradeVOS = courseSelectionService.ListGrade(cid);
        System.out.println(gradeVOS.getClass());
        return R.ok().message("获取成功").data("gradeVOS",gradeVOS);
    }
    @ApiOperation(value = "excel表批量导入教师信息（管理员权限）")
    @PostMapping("/Excel/import")
    public R teacherExcel(@ApiParam(value = "Excel数据字典文件",required = true)
                       @RequestParam("file") MultipartFile file) {

        try {
            InputStream inputStream = file.getInputStream();
            teacherInfoService.importData(inputStream);
            return R.ok().message("数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException((ResponseEnum.UPLOAD_ERROR),e);
        }
    }


}

